import datetime
import tornado.web
import tornado.ioloop
import kg_process as process
import json

from kg_dataexcel import export_excel


def get_param(request):
    paramt = request.body
    if paramt is None or len(paramt) < 1:
        paramts = request.values.to_dict()
    else:
        paramts = json.loads(request.body.decode())
    return paramts


class InitHandler(tornado.web.RequestHandler):
    '''
    接口初始化
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass


class DiquFabinHandler(tornado.web.RequestHandler):
    '''
    不同地区发病率
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf-8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):
        # self.set_header("Access-Control-Allow-Origin", "*")
        try:
            # params = get_param(self.request)
            param = get_param(self.request)
            result = {}
            name = param.get('category_name')
            if name is None or name == '':
                sql = "select * from diqu_fabin "
            else:
                sql = "select * from diqu_fabin where category_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class AgeFabinHandler(tornado.web.RequestHandler):
    '''
    不同年龄发病率
    '''

    ##
    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    ##
    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('category_name')
            if name is None or name == '':
                sql = "select  CASE max_age WHEN 1 THEN \'0~9\'" \
                      " WHEN 2 THEN \'10~19\' " \
                      "WHEN 3 THEN \'20~29\'" \
                      "WHEN 4 THEN \'30~39\'" \
                      "WHEN 5 THEN \'40~49\'" \
                      "WHEN 6 THEN \'50~59\' " \
                      "WHEN 7 THEN \'60~69\' " \
                      "WHEN 8 THEN \'70~79\' " \
                      "WHEN 9 THEN \'80~89\' " \
                      "WHEN 10 THEN \'90~99\'" \
                      "WHEN 11 THEN \'100~109\' " \
                      "WHEN 12 THEN \'110~119\' " \
                      "ELSE \'0\' end max_age, " \
                      "category_name, age_fabinlv from age_fabin order by max_age"
            else:
                sql = "select CASE max_age WHEN 1 THEN \'0~9\'" \
                      " WHEN 2 THEN \'10~19\' " \
                      "WHEN 3 THEN \'20~29\'" \
                      "WHEN 4 THEN \'30~39\'" \
                      "WHEN 5 THEN \'40~49\'" \
                      "WHEN 6 THEN \'50~59\' " \
                      "WHEN 7 THEN \'60~69\' " \
                      "WHEN 8 THEN \'70~79\' " \
                      "WHEN 9 THEN \'80~89\' " \
                      "WHEN 10 THEN \'90~99\'" \
                      "WHEN 11 THEN \'100~109\' " \
                      "WHEN 12 THEN \'110~119\' " \
                      "ELSE \'0\' end max_age, " \
                      "category_name, age_fabinlv  from age_fabin where category_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class GenderFabinHandler(tornado.web.RequestHandler):
    '''
     不同性别发病率
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)

            result = {}
            name = params.get('category_name')
            if name is None or name == '':
                sql = "select CASE gender WHEN 'F' THEN '女' WHEN 'M' THEN '男'  ELSE '未知'\
                      end gender,category_name,gender_fabinlv from gender_fabin "
            else:
                sql = "select CASE gender WHEN 'F' THEN '女' WHEN 'M' THEN '男'  ELSE '未知' \
                      end gender,category_name,gender_fabinlv from gender_fabin where category_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)
        self.write(ret)


class YongyaoFabinHandler(tornado.web.RequestHandler):
    '''
    常见药品
    jibin_yongyao
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)

            result = {}
            name = params.get('category_name')
            if name is None or name == '':
                sql = "select * from jibin_yongyao "
            else:
                sql = "select * from jibin_yongyao where category_name = \'" + name + "\' order by jibin_yongyaobi limit 10"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class ZhenliaoFabinHandler(tornado.web.RequestHandler):
    '''
    常见诊疗
    jibin_yongyao
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('category_name')
            if name is None or name == '':
                sql = "select * from jibin_zhenliao "
            else:
                sql = "select * from jibin_zhenliao where category_name = \'" + name + "\' order by jibin_zhenliaobi limit 10"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class BinFaHandler(tornado.web.RequestHandler):
    '''
    常见并发疾病
     {
            "a_code_category"："001",//疾病id
            "a_category_name": "一类糖尿病",//先患疾病名称
            "b_code_category":"web002",
            "b_category_name": "二类糖尿病",//后患疾病名称
            "confidence":0.2,//转移概率
        },
    jibin_yongyao
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('category_name')
            if name is None or name == '':
                sql = "select * from changjian_binfa "
            else:
                sql = "select * from changjian_binfa where a_category_name = \'" + name + "\' order by confidence limit 10"

            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class RelationsHandler(tornado.web.RequestHandler):
    '''
    常见并发疾病
     "data":[
       {
            "a_code_category"："001",//疾病id
            "a_category_name": "原发性高血压",//先患疾病名称
            "a_fabinlv": 0.2,//先患疾病名称发病率
            "b_code_category":"002",
            "b_category_name": "高血压肾病",//后患疾病名称
            "b_fabinlv": 0.11,//后患疾病名称发病率
            "confidence":0.18,//转移概率
        }],
    zong_fabin  发病率
    changjian_binfa 转移

    select  *  from changjian_binfa,zong_fabin
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            a_name = params.get('a_category_name')
            b_name = params.get('b_category_name')
            sql = "SELECT a.a_category_name,b1.fabinlv as a_fabinlv,a.b_category_name," \
                  "a.confidence,b2.fabinlv as b_fabinlv FROM changjian_binfa a " \
                  "LEFT JOIN zong_fabin b1 ON a.a_category_name = b1.category_name " \
                  "LEFT JOIN zong_fabin b2 ON a.b_category_name = b2.category_name  " \
                  "WHERE a.a_category_name =\'" + a_name + "\' AND a.b_category_name = " + "\'" + b_name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class JibinItemHandler(tornado.web.RequestHandler):
    '''
     与疾病相关药品
    "data":[
       {
            "code_category"："001",//疾病id
            "category_name": "糖尿病",//疾病名称
            "n_item_name":"盐酸二甲双胍缓释片",//药品名称
            "jibin_yongyaobi":0.18,//用药占比
        }],

        jibin_yongyao
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('category_name')
            if name is None or name == '':
                sql = "select * from jibin_yongyao "
            else:
                sql = "select * from jibin_yongyao where category_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class ItemJibinHandler(tornado.web.RequestHandler):
    '''
     与药品相关疾病
    "data":[
       {
            "code_category"："001",//疾病id
            "n_item_name":"盐酸二甲双胍缓释片",//药品名称
            "category_name": "糖尿病",//疾病名称
            "yongyao_jibinbi":0.18,//使用率
        }],
        yongyao_jibin
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('n_item_name')
            if name is None or name == '':
                sql = "select * from yongyao_jibin "
            else:
                sql = "select * from yongyao_jibin where n_item_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class GenderItemHandler(tornado.web.RequestHandler):
    '''
     不同性别用药率
    {"n_item_name":"药品名称"}
    {
        "msg": "查询成功！",
        "data":[
           {
                "gender"："F",//性别（F 女 /M 男）
                "n_item_name": "药品",//药品
                "yongyao_genderbi": 0.2,//使用率
            }, {
                "gender"："M",//性别（F 女 /M 男）
                "n_item_name": "药品",//药品
                "yongyao_genderbi": 0.2,//使用率
            }]
        "code": 200,
    }
        jibin_yongyao_gender
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('n_item_name')
            if name is None or name == '':
                sql = "select CASE gender WHEN 'F' THEN '女' WHEN 'M' THEN '男'  ELSE '未知'\
                      end gender,code_category,category_name,n_item_id,n_item_name,yongyao_genderbi from jibin_yongyao_gender "
            else:
                sql = "select CASE gender WHEN 'F' THEN '女' WHEN 'M' THEN '男'  ELSE '未知'\
                      end gender,code_category,category_name,n_item_id,n_item_name,yongyao_genderbi from jibin_yongyao_gender where n_item_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class AgeItemHandler(tornado.web.RequestHandler):
    '''
     不同年龄用药率

        jibin_yongyao_age
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('n_item_name')
            sql = "select CASE max_age WHEN 1 THEN '0~9' \
            						WHEN 2 THEN '10~19'\
            						WHEN 3 THEN '20~29'\
            						WHEN 4 THEN '30~39'\
            						WHEN 5 THEN '40~49'\
            						WHEN 6 THEN '50~59'\
            						WHEN 7 THEN '60~69'\
            						WHEN 8 THEN '70~79'\
            						WHEN 9 THEN '80~89'\
            						WHEN 10 THEN '90~99'\
            						WHEN 11 THEN '100~109'\
            						WHEN 12 THEN '110~119'\
                        ELSE '0' end max_age,code_category,category_name,n_item_id,n_item_name,yongyao_agebi from jibin_yongyao_age "
            if name is None or name == '':
                other = " order by max_age"
            else:
                other = " where n_item_name = \'" + name + "\' order by max_age"
            result['data'] = process.get_data(sql+other)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class ZhenBinHandler(tornado.web.RequestHandler):
    '''
     诊疗相关疾病
     zhenliao_jibin
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('n_item_name')
            if name is None or name == '':
                sql = "select * from zhenliao_jibin "
            else:
                sql = "select * from zhenliao_jibin where n_item_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class ZhenBinHandler(tornado.web.RequestHandler):
    '''
     诊疗相关疾病
     zhenliao_jibin
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('n_item_name')
            if name is None or name == '':
                sql = "select * from zhenliao_jibin "
            else:
                sql = "select * from zhenliao_jibin where n_item_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class GenderLiaoHandler(tornado.web.RequestHandler):
    '''
     不同性别诊疗率
     jibin_zhenliao_gender
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('n_item_name')
            if name is None or name == '':
                sql = "select CASE gender WHEN 'F' THEN '女' WHEN 'M' THEN '男'  ELSE '未知'\
                      end gender,code_category,category_name,n_item_id,n_item_name,zhenliao_genderbi from jibin_zhenliao_gender "
            else:
                sql = "select CASE gender WHEN 'F' THEN '女' WHEN 'M' THEN '男'  ELSE '未知'\
                      end gender,code_category,category_name,n_item_id,n_item_name,zhenliao_genderbi from jibin_zhenliao_gender where n_item_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class AgeLiaoHandler(tornado.web.RequestHandler):
    '''
     不同年龄诊疗率
     jibin_zhenliao_age
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):

        try:
            params = get_param(self.request)
            result = {}
            name = params.get('n_item_name')
            if name is None or name == '':
                sql = "select * from jibin_zhenliao_age "
            else:
                sql = "select * from jibin_zhenliao_age where n_item_name = \'" + name + "\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)
        self.write(ret)


class GetNameHandler(tornado.web.RequestHandler):
    '''
     模糊查询姓名
     zhenliao_lv
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def post(self, *args):
        try:
            params = get_param(self.request)
            result = {}
            name = params.get('category_name')
            if name is None or name == '':
                sql = "select category_name from zong_fabin "
            else:
                sql = "select category_name from zong_fabin where  category_name like \'%" + name + "%\'"
            result['data'] = process.get_data(sql)
            result['msg'] = 'success'
            result['code'] = 200
            ret = json.dumps(result, ensure_ascii=False)
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)

        self.write(ret)


class FaBinExcelHandler(tornado.web.RequestHandler):
    '''
     发病情况下载
     fabin_lv
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def get(self, *args):
        try:
            sql = "select * from fabin_lv"
            head = ["ICD10", "疾病名称", "年份", "地区", "年龄","性别","行业","职业", "发病人数", "被保险人数", "用药占比"]
            line = ["code_category", "category_name", "y", "addr","max_age","gender","hangye","occup_code", "num_fabin", "num_baoxian",
                    "fabinlv"]
            output = export_excel(sql,head,line)
            nowtime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            self.set_header("Content-Type", "application/octet-stream")
            # 设置文件名
            self.set_header("Content-Disposition", "attachment; filename=fabinlv_%s.xls" % nowtime)
            return self.write(output.getvalue())
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)
            self.write(ret)


class YongYaoExcelHandler(tornado.web.RequestHandler):
    '''
     用药情况下载
     yongyao_lv
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def get(self, *args):

        try:
            sql = "select * from yongyao_lv"
            head = ["ICD10","疾病名称","年份","地区","药品名","用药人数","患病人数","用药占比"]
            line = ["code_category","category_name","y","addr","n_item_name","num_yongyao","num_huanbin","yongyaobi"]
            output = export_excel(sql,head,line)
            nowtime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            self.set_header("Content-Type", "application/octet-stream")
            # 设置文件名
            self.set_header("Content-Disposition", "attachment; filename=yongyaolv_%s.xls" % nowtime)
            self.write(output.getvalue())
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)
            self.write(ret)


class ConfExcelHandler(tornado.web.RequestHandler):
    '''
    诊疗手段情况下载
     zhenliao_lv
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def get(self, *args):
        try:
            sql = "select * from zhenliao_lv"
            head = ["ICD10", "疾病名称", "年份", "地区", "诊疗手段", "诊疗人数", "患病人数", "诊疗占比"]
            line = ["code_category", "category_name", "y", "addr", "n_item_name", "num_zhenliao", "num_huanbin",
                    "zhenliaobi"]
            output = export_excel(sql, head, line)
            nowtime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            self.set_header("Content-Type", "application/octet-stream")
            # 设置文件名
            self.set_header("Content-Disposition", "attachment; filename=zhenliaolv_%s.xls" % nowtime)
            self.write(output.getvalue())
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)
            self.write(ret)


class ZhenLiaoExcelHandler(tornado.web.RequestHandler):
    '''
    疾病转移概率下载
     fabin_support_confidence
    '''

    def initialize(self):
        self.set_default_header()

    def set_default_header(self):
        print("setting headers!!!")
        self.set_header('Access-Control-Allow-Origin', '*')
        # self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        self.set_header('Content-Type', 'application/json; charset=utf8')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')

    def options(self):
        pass

    def get(self, *args):
        try:
            sql = "select * from fabin_support_confidence"
            head = ["地区", "已患疾病", "转移疾病", "置信度", "支持度"]
            line = ["addr", "a_category_name", "b_category_name", "confidence",
                    "support"]
            output = export_excel(sql, head, line)
            nowtime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            self.set_header("Content-Type", "application/octet-stream")
            # 设置文件名
            self.set_header("Content-Disposition", "attachment; filename=supportlv_%s.xls" % nowtime)
            self.write(output.getvalue())
        except:
            result = {'msg': 'input error', 'code': 400, 'result': {}}
            ret = json.dumps(result, ensure_ascii=False)
            self.write(ret)


def get_app():
    return tornado.web.Application([(r'/kg/get_diqu_fabins', DiquFabinHandler),
                                    (r'/kg/get_age_fabins', AgeFabinHandler),
                                    (r'/kg/get_gender_fabins', GenderFabinHandler),
                                    (r'/kg/get_jibin_yongyaos', YongyaoFabinHandler),
                                    (r'/kg/get_jibin_zhenliaos', ZhenliaoFabinHandler),
                                    (r'/kg/get_changjian_binfas', BinFaHandler),
                                    (r'/kg/get_ill_relations', RelationsHandler),
                                    (r'/kg/get_item_categorys', JibinItemHandler),
                                    (r'/kg/get_category_items', ItemJibinHandler),
                                    (r'/kg/get_gender_items', GenderItemHandler),
                                    (r'/kg/get_age_items', AgeItemHandler),
                                    (r'/kg/get_zhenliao_jibins', ZhenBinHandler),
                                    (r'/kg/get_gender_zhenliaos', GenderLiaoHandler),
                                    (r'/kg/get_age_zhenliaos', AgeLiaoHandler),
                                    (r'/kg/get_like_name', GetNameHandler),
                                    (r'/kg/get_fabin_lv_excel', FaBinExcelHandler),
                                    (r'/kg/get_yongyao_lv_excel', YongYaoExcelHandler),
                                    (r'/kg/get_confidence_lv_excel', ConfExcelHandler),
                                    (r'/kg/get_zhenliao_lv_excel', ZhenLiaoExcelHandler)])
